package com.StarStudio.Controller;

import com.StarStudio.Service.PanicBuyingOrdersService;
import com.ruoyi.common.core.Entity.*;
import com.StarStudio.Service.CouponsService;
import com.StarStudio.Service.PanicBuyingCouponsService;
import com.StarStudio.Utils.QueryPageUtils;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@RestController
@RequestMapping("/pb_coupons")
@Api(tags = "抢购优惠券接口")
public class PanicBuyingCouponsController {

    @Autowired
    PanicBuyingCouponsService panicBuyingCouponsService;

    @Autowired
    RedisService redisService;

    @Autowired
    CouponsService couponsService;

    @Autowired
    PanicBuyingOrdersService panicBuyingOrdersService;

    /**
     * 带搜索条件分页查询（商家后台端）
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @GetMapping("/page")
    @ApiOperation("抢购优惠券分页接口 -> 支持条件检索，检索条件封装在抢购优惠券对象PanicBuyingCoupons中。如需分页，必传pageNum和pageSize")
    public PageResult findPanicBuyingCouponsList(PanicBuyingCoupons panicBuyingCoupons){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<PanicBuyingCoupons> panicBuyingCouponsList;
        long totalRecord;
        try {
            panicBuyingCouponsList = panicBuyingCouponsService.findPanicBuyingCouponsList(panicBuyingCoupons);
            totalRecord = panicBuyingCouponsService.findTotalRecord();
            pageInfo = new PageInfo<>(panicBuyingCouponsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_COUPONS_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_COUPONS_SUCCESS,pageInfo.getTotal(),panicBuyingCouponsList,totalRecord);
    }

    /**
     * 带搜索条件分页查询（APP端）
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @GetMapping("/list")
    @ApiOperation("抢购优惠券分页接口（APP端）-> 支持条件检索，检索条件封装在抢购优惠券对象PanicBuyingCoupons中。如需分页，必传pageNum和pageSize")
    public Result findPanicBuyingCouponsResultList(PanicBuyingCoupons panicBuyingCoupons){
        List<PanicBuyingCoupons> panicBuyingCouponsList;
        List<CouponsResult> list = null;
        try {
            panicBuyingCouponsList = panicBuyingCouponsService.findPanicBuyingCouponsList(panicBuyingCoupons);
            if (panicBuyingCouponsList.size() > 0){
                list = new ArrayList<>();
                for (PanicBuyingCoupons pbCoupons : panicBuyingCouponsList) {
                    CouponsResult couponsResult = new CouponsResult(couponsService.findByCouponsId(pbCoupons.getCoupons_id()),pbCoupons);
                    if (new Timestamp(new Date().getTime()).before(pbCoupons.getPanic_buying_start_time())){
                        couponsResult.setRemainBeginSeconds((int)((pbCoupons.getPanic_buying_start_time().getTime() - new Date().getTime())/1000));
                        couponsResult.setRemainEndSeconds((int)((pbCoupons.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }else if (new Timestamp(new Date().getTime()).after(pbCoupons.getPanic_buying_end_time())) {
                        couponsResult.setRemainBeginSeconds(-1);
                        couponsResult.setRemainEndSeconds(-1);
                    }else {
                        couponsResult.setRemainBeginSeconds(0);
                        couponsResult.setRemainEndSeconds((int)((pbCoupons.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }
                    list.add(couponsResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_GOODS_SUCCESS,list);
    }


    /**
     * 更新抢购优惠券信息
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "更新抢购优惠券", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("抢购优惠券更新（修改）接口 -> 抢购优惠券ID、优惠券ID、抢购价格（鲜豆）、抢购优惠券库存数量、抢购开始时间、抢购结束时间、抢购状态不能为空")
    public Result updatePanicBuyingCoupons(@RequestBody PanicBuyingCoupons panicBuyingCoupons){
        if (panicBuyingCoupons == null || panicBuyingCoupons.getPanic_buying_coupons_id() == null || panicBuyingCoupons.getCoupons_id() == null ||
            panicBuyingCoupons.getPanic_buying_price() == null || panicBuyingCoupons.getPanic_buying_coupons_stock() == null || panicBuyingCoupons.getPanic_buying_start_time() == null
            || panicBuyingCoupons.getPanic_buying_end_time() == null || panicBuyingCoupons.getPanic_buying_status() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            int i = panicBuyingCouponsService.updatePanicBuyingCoupons(panicBuyingCoupons);
            if (i > 0){
                // 将抢购商品库存更新到 Redis缓存中
                redisService.setCacheObject("panic_buying_coupons:" + panicBuyingCoupons.getCoupons_id(),panicBuyingCoupons.getPanic_buying_coupons_stock());
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            if (e.getMessage().equals("库存不能小于零！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.STOCK_CAN_NOT_LESS_THAN_ZERO);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_PANIC_BUYING_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_PANIC_BUYING_COUPONS_SUCCESS);
    }

    /**
     * 新增抢购优惠券
     * @param panicBuyingCoupons 抢购优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "新增抢购优惠券",businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("抢购优惠券新增接口 -> 优惠券ID、抢购价格（鲜豆）、抢购优惠券库存数量、抢购开始时间、抢购结束时间、抢购状态不能为空")
    public Result AddPanicBuyingCoupons(@RequestBody PanicBuyingCoupons panicBuyingCoupons){
        if (panicBuyingCoupons == null  || panicBuyingCoupons.getCoupons_id() == null ||
            panicBuyingCoupons.getPanic_buying_price() == null || panicBuyingCoupons.getPanic_buying_coupons_stock() == null || panicBuyingCoupons.getPanic_buying_start_time() == null
            || panicBuyingCoupons.getPanic_buying_end_time() == null || panicBuyingCoupons.getPanic_buying_status() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            panicBuyingCouponsService.AddPanicBuyingCoupons(panicBuyingCoupons);
            // 将抢购优惠券库存更新到 Redis缓存中
            redisService.setCacheObject("panic_buying_coupons:" + panicBuyingCoupons.getCoupons_id(),panicBuyingCoupons.getPanic_buying_coupons_stock());
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("优惠券库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_COUPONS_STOCK);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_PANIC_BUYING_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_PANIC_BUYING_COUPONS_SUCCESS);
    }

    /**
     * 删除抢购优惠券
     * @param panic_buying_coupons_ids 抢购优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "删除抢购优惠券",businessType = BusinessType.DELETE)
    @DeleteMapping("/{panic_buying_coupons_ids}")
    @ApiOperation("抢购优惠券删除接口 -> path传抢购优惠券ID")
    public Result DeletePanicBuyingCoupons(@PathVariable Long[] panic_buying_coupons_ids){
        if (panic_buying_coupons_ids == null || panic_buying_coupons_ids.length == 0){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            for (Long panic_buying_coupons_id : panic_buying_coupons_ids) {
                panicBuyingCouponsService.DeletePanicBuyingCoupons(panic_buying_coupons_id);
                //获取对应优惠券ID
                Long couponsId = panicBuyingCouponsService.findCouponsIdByRecordId(panic_buying_coupons_id);
                if (couponsId == null){
                    return new Result(HttpStatusCode.ERROR,MessageConstant.COUPON_NOT_EXIST);
                }
                // 删除Redis中抢购优惠券的缓存
                redisService.deleteObject("panic_buying_coupons:" + couponsId);
                //删除Redis中抢购优惠券订单缓存
                List<Long> userIdList = panicBuyingOrdersService.findUserIdListByCouponsId(couponsId);
                if (!CollectionUtils.isEmpty(userIdList)){
                    for (Long userId : userIdList) {
                        redisService.deleteObject("panic_buying_coupons_order:" + userId + ":" + couponsId);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_PANIC_BUYING_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_PANIC_BUYING_COUPONS_SUCCESS);
    }
}
